using System;
using UnityEngine;

[AddComponentMenu("ImageEffect/Radial Blur")]
[ExecuteInEditMode]
public class RadialBlur : MonoBehaviour
{
	private static RadialBlur _instance;
	public Shader RadialBlurShader;

	private Material RadialBlurMaterial;

	[Range(0f, 1f)]
	public float SampleDist = 0.6f;

	[Range(1f, 5f)]
	public float SampleStrength = 2f;

	private bool isSupported = true;

	private void Start()
	{
		_instance = this;
		CheckSupport();
		CreateMaterials();
	}

	public static void open()
	{
		if (!_instance && Camera.allCamerasCount > 0)
		{
			_instance = Camera.allCameras[0].gameObject.GetComponent<RadialBlur>();
		}
		if (!_instance && Camera.allCamerasCount > 0)
		{
			_instance = Camera.allCameras[0].gameObject.AddComponent<RadialBlur>();
		}
		if (_instance)
		{
			_instance.enabled = true;
		}
	}

	public static void close()
	{
		if (_instance)
		{
			_instance.enabled = false;
		}
	}

	public static bool isOpen()
	{
		if (!_instance) return false;
		return _instance.enabled;
	}

	private Shader _RadialBlurShader
	{
		get
		{
			if (!RadialBlurShader)
			{
				//RadialBlurShader = Shader.Find("ImageEffect/RadialBlur");
				RadialBlurShader = Shader.Find("Unlit/RadialBlur");
			}
			return RadialBlurShader;
		}

	}

	private void CreateMaterials()
	{
		if (!RadialBlurMaterial)
		{
			RadialBlurMaterial = new Material(_RadialBlurShader);
			RadialBlurMaterial.hideFlags = HideFlags.HideAndDontSave;
		}
	}

	private bool Supported()
	{
		return SystemInfo.supportsImageEffects && SystemInfo.supportsRenderTextures && _RadialBlurShader.isSupported;
	}

	private bool CheckSupport()
	{
		if (!Supported())
		{
			isSupported = false;
			return false;
		}
		return true;
	}

	private void OnRenderImage(RenderTexture sourceTexture, RenderTexture destTexture)
	{
		CreateMaterials();
		if (RadialBlurMaterial)
		{

			RadialBlurMaterial.SetVector("_Center", new Vector2(0.5f, 0.5f));
			RadialBlurMaterial.SetFloat("_BlurScale", SampleStrength / 100);
			Graphics.Blit(sourceTexture, destTexture, RadialBlurMaterial);  //将最终图像赋值给输出图像
		}
	}

	public void Reset()
	{
		if ((bool)RadialBlurMaterial)
		{
			UnityEngine.Object.DestroyImmediate(RadialBlurMaterial);
			RadialBlurMaterial = null;
		}
		CreateMaterials();
	}

	public bool IsSupported()
	{
		return isSupported;
	}

	public void OnDestroy()
	{
		if ((bool)RadialBlurMaterial)
		{
			UnityEngine.Object.DestroyImmediate(RadialBlurMaterial);
			RadialBlurMaterial = null;
		}
	}
}
